package com.linln.common.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.HttpPutFormContentFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by wangfan on 2019-01-04 下午 3:40.
 */
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {

    @Bean
    public FilterRegistrationBean filterRegistrationBeanDemo() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(new CrossFilter());
        registrationBean.addUrlPatterns("/*");
        registrationBean.setName("filter1Name");
        return registrationBean;
    }

    // 支持跨域访问
    @Override
    public void addCorsMappings(CorsRegistry registry) {
//        registry.addMapping("/**").allowedMethods("GET", "POST", "DELETE", "PUT").maxAge(3600).allowedHeaders("Content-Type, x-requested-with, X-Custom-Header, Authorization, token");
        registry.addMapping("/**").allowedMethods("GET", "POST", "DELETE", "PUT").maxAge(3600).allowedHeaders("x-requested-with,Authorizationaccept,X-Custom-Header,Authorization,origin,content-type,token,secret");
    }

    // 支持PUT请求
    @Bean
    public HttpPutFormContentFilter httpPutFormContentFilter() {
        return new HttpPutFormContentFilter();
    }

/*    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                response.setContentType("text/html;charset=utf-8");
                String appid = request.getHeader("appid");
                String sign = request.getHeader("sign");
                String nonce = request.getHeader("nonce");
                String timestamp = request.getHeader("timestamp");

                if (Strings.isEmpty(appid) || Strings.isEmpty(timestamp) || Strings.isEmpty(nonce) || Strings.isEmpty(sign)) {
                    response.getWriter().println(JsonResult.error("请求头缺少授信参数"));
                    return false;
                }

                // 限制为（含）60秒以内发送的请求
                long time = 60000;
                long now = System.currentTimeMillis();
                if (now - Long.parseLong(timestamp) > time) {
                    response.getWriter().println(JsonResult.error("请求发起时间超过服务器限制时间"));
                    return false;
                }
                // 校验appid
                if (!APPID.equalsIgnoreCase(appid)) {
                    response.getWriter().println(JsonResult.error("appid参数错误"));
                    return false;
                }

                if (redisUtil.hHasKey("third_party_key", APPID + nonce)) {
                    response.getWriter().println(JsonResult.error("请不要发送重复的请求"));
                    return false;
                } else {
                    // 如果nonce没有存在缓存中，则加入，并设置失效时间（秒）
                    redisUtil.hset("third_party_key", APPID + nonce, nonce);
                    redisUtil.expire("third_party_key", (int)time/1000);
                }
                Map<String, String> signObj = new HashMap<>(3);
                signObj.put("appid", appid);
                signObj.put("timestamp", timestamp);
                signObj.put("nonce", nonce);
                String mySign = SignUtil.getSign(signObj, SECRET);
                // 校验签名
                if (!mySign.equals(sign)) {
                    response.getWriter().println(JsonResult.error("签名信息错误"));
                    return false;
                }
                return true;
            }
        }).addPathPatterns("/**");
    }*/


    //解决跨域的
    class CrossFilter implements Filter {

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {

        }

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            HttpServletResponse res = (HttpServletResponse) servletResponse;
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            res.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
            res.setHeader("Access-Control-Allow-Methods", "POST, GET,PUT, OPTIONS, DELETE,PUT");
//            res.setHeader("Access-Control-Allow-Headers", "x-requested-with, Authorization, origin, content-type, token");
            res.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorizationaccept,origin,content-type,token,secret,timestamp,nonce,sign,appid");
            //允许跨域请求中携带cookie
            res.setHeader("Access-Control-Allow-Credentials", "true");
            filterChain.doFilter(servletRequest, servletResponse);
        }

        @Override
        public void destroy() {

        }
    }
}
